package com.wjw.java.thread;

/**
 * 用户线程：也叫工作线程,当线程的任务执行完或通知方式结束
 * 守护线程：一般是为工作线程服务的,当所有工作线程(用户线程)执行完毕,守护线程自动结束
 * 垃圾回收机制：就是一种守护线程
 */
public class DaemonThread {
    public static void main(String[] args) {
        //将子线程设置为守护线程,当main线程执行完毕,守护线程也将执行完
        MyDeamonThread deamon = new MyDeamonThread();
        Thread thread = new Thread(deamon,"守护线程:");
        thread.setDaemon(true);//设置为守护线程
        thread.start();

        //main线程运行完毕,守护线程也将执行完
        for (int i = 0; i < 10; i++) {
            String name = Thread.currentThread().getName();
            try {
                System.out.println(name+":正在运行中..."+ (i+1));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
class MyDeamonThread implements Runnable{
    int num = 0;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for (;;){//无线循环
            try {
                System.out.println(name+"正在运行中..."+ (++num));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}